package com.umeox.iqibla.azkar.ui

import android.content.Context
import android.os.Handler
import android.os.Vibrator
import android.view.View
import android.widget.ImageView
import com.umeox.iqibla.azkar.R
import com.umeox.iqibla.azkar.db.AppDatabase
import com.umeox.iqibla.azkar.db.Azkar
import com.umeox.iqibla.azkar.db.AzkarDao
import com.umeox.iqibla.azkar.utils.DateUtils
import com.umeox.iqibla.azkar.utils.LongClickUtils
import com.umeox.iqibla.azkar.utils.OnNoDoubleClickListener
import com.umeox.moto.common.executor.ThreadExecutor
import com.umeox.moto.common.log.Logger
import com.umeox.moto.watch.themes.app.ThemeFragment
import com.umeox.moto.watch.themes.widget.TextView
import com.umeox.watch.moto.apiclient.model.ChantsCountDTO
import com.umeox.watch.moto.dataservice.proxy.PullApiClientProxy
import java.text.DecimalFormat
import java.text.DecimalFormatSymbols
import java.util.Locale

/**
 * Created by Rambo 2024/3/28/0028
 * Describe:
 */
class AzkarFragment : ThemeFragment() {

    private lateinit var mCountResultTv: TextView
    private lateinit var mCountIv: ImageView
    private var mCount: Int = 0
    private var mTodayAzkarCount: Int = 0
    //处理跨天的变量，存储昨天的内存缓存数据
    private var mYesterdayAzkarCount: Int = 0

    private lateinit var azkarDao : AzkarDao

    override fun getLayoutId(): Int {
        return R.layout.frag_azkar
    }

    override fun initView(rootView: View) {
        azkarDao = AppDatabase.get().azkarDao()
        mCountResultTv = rootView.findViewById(R.id.tv_count_result)
        mCountIv = rootView.findViewById(R.id.iv_count)
        mCountIv.isHapticFeedbackEnabled = false
        mCountIv.setOnClickListener(object : OnNoDoubleClickListener() {

            override fun onNoDoubleClick(v: View?) {
                vibrate(50)
                mCount++
                mCountResultTv.text = formatCount(mCount)
//                if (mCount / 5 == 0) {
                //需要判断是否隔天了
                //当天时间戳大于数据库最新一条数据的时间戳则说明已经隔天
                saveAzkarCount()

//                }
            }
        })

        LongClickUtils.setLongClick(Handler(),mCountIv,3000L) {
            vibrate(300)
            mCount = 0
            mTodayAzkarCount =
                AppDatabase.get().azkarDao().queryTodayAzkarCount(DateUtils.getTodayMillis())
            mCountResultTv.text = "00000"
            //上报赞念数据
            uploadChants()
            true
        }

//        mCountIv.setOnLongClickListener {
//            vibrate(300)
//            mCount = 0
//            mTodayAzkarCount = AppDatabase.get().azkarDao().queryTodayAzkarCount(DateUtils.getTodayMillis())
//            mCountResultTv.text = "00000"
//            return@setOnLongClickListener true
//        }
        if (DateUtils.getTodayMillis() > azkarDao.queryLatestRecordTodayMillis()
        ) {
            azkarDao.save(Azkar(DateUtils.getTodayMillis(), 0, false))
        }
        mTodayAzkarCount = azkarDao.queryTodayAzkarCount(DateUtils.getTodayMillis())
    }

    private fun uploadChants() {
        ThreadExecutor.getInstance().io().execute {
            //查询出所有没有上传的数据
            val azkarDao = AppDatabase.get().azkarDao()
            val notUploadAzkarList = azkarDao.loadNoUploadList()
            notUploadAzkarList?.apply {
                val chantsCountDTOList = mutableListOf<ChantsCountDTO>()
                notUploadAzkarList.forEach {
                    val chantsCountDTO = ChantsCountDTO()
                    chantsCountDTO.date = com.umeox.moto.common.utils.DateUtils.formatDateTime(
                        it.todayMillis * 1000L,
                        "yyyyMMddZ"
                    )
                    chantsCountDTO.amount = it.count
                    chantsCountDTOList.add(chantsCountDTO)
                }
                if(chantsCountDTOList.isNotEmpty()){
                    val result = PullApiClientProxy.fetchBinder().uploadChants(chantsCountDTOList)
                    Logger.e(if(result) "赞念计数上传成功" else "赞念计数上传失败")
                    //更新本地数据库的上传标记为已上传
                    if(result){
                        notUploadAzkarList.forEach {
                            it.isUpload = true
                            azkarDao.save(notUploadAzkarList)
                        }
                    }
                }
            }
        }
    }


    private fun saveAzkarCount() {
        val needSaveCount: Int
        if (DateUtils.getTodayMillis() > azkarDao.queryLatestRecordTodayMillis()
        ) {
            needSaveCount = mCount + mTodayAzkarCount - azkarDao.queryLatestRecordCount()
            mYesterdayAzkarCount = azkarDao.queryLatestRecordCount() - mTodayAzkarCount
            if (mTodayAzkarCount > 0) {
                mTodayAzkarCount = 0
            }
        } else {
            needSaveCount = mCount - mYesterdayAzkarCount + mTodayAzkarCount
        }
        azkarDao.save(Azkar(DateUtils.getTodayMillis(), needSaveCount, false))
    }

    private fun vibrate(milliseconds: Long) {
        val mVibrator = mContext.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
        mVibrator.vibrate(milliseconds)
    }

    private fun formatCount(count: Int): String {
        val df = DecimalFormat("00000", DecimalFormatSymbols(Locale.ENGLISH))
        return df.format(count)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        if (mCount + mTodayAzkarCount > 0) {
            azkarDao.save(Azkar(DateUtils.getTodayMillis(), mCount + mTodayAzkarCount, false))
        }
    }
}